<template>
  <el-card>
    <el-tabs type="border-card">
      <el-tab-pane label="账号密码登录">
        <el-form
          ref="formRef"
          :rules="rules"
          label-position="left"
          label-width="100px"
          :model="loginUser"
          style="max-width: 460px"
          status-icon
        >
          <el-form-item label="用户名" prop="name">
            <el-input v-model="loginUser.name" />
          </el-form-item>
          <el-form-item label="密码" prop="pass">
            <el-input v-model="loginUser.pass" type="password" />
          </el-form-item>
          <el-form-item @click="refreshCode()">
            <el-image
              style="width: 200px"
              :src="captcha"
              fit="contain"
            ></el-image>
          </el-form-item>
          <el-form-item label="验证码" prop="code">
            <el-input
              v-model="loginUser.code"
              @keyup.enter="doLogin(formRef)"
            />
          </el-form-item>
        </el-form>
        <div class="bt-login">
          <el-button type="primary" @click="doLogin(formRef)">登录</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="2FA 登录">
        <el-form
          :model="tempForm"
          :rules="tempFormRules"
          ref="tempFormRef"
          status-icon
          label-width="120px"
        >
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="tempForm.userName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="2FA 密码" prop="tempPass">
            <el-input
              v-model="tempForm.tempPass"
              autocomplete="off"
              @keyup.enter="submitTempForm(tempFormRef)"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitTempForm(tempFormRef)"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script setup>
import { baseURL } from "../../config/axios.config";
import { login, loginBy2faCode } from "@/api/userAPI";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const formRef = ref();
const store = useStore();
const captcha = ref("");
const t = ref("");
const loginUser = reactive({
  name: "admin",
  pass: "admin",
  code: "",
});
const router = useRouter();
const tempForm = reactive({});
const tempFormRef = ref();
const tempFormRules = {
  userName: [{ required: true, message: "请输入 用户名", trigger: "blur" }],
  tempPass: [{ required: true, message: "请输入 2FA 密码", trigger: "blur" }],
};
const rules = reactive({
  name: [
    { required: true, message: "请输入 用户名", trigger: "blur" },
    {
      min: 4,
      max: 18,
      message: "用户名至少是 4 位数, 最多 18 位数",
      trigger: "blur",
    },
  ],
  pass: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 4, max: 18, message: "密码至少是 4 位数", trigger: "blur" },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});
const doLogin = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      login(loginUser, t.value)
        .then((data) => {
          ElMessage.success(data.message);
          store.commit("setLoggedUser", data.data);
          router.push("/");
        })
        .catch(() => {
          // 登录异常一般是 验证码错误, 所以这里刷新下验证码
          refreshCode();
        });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const submitTempForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loginBy2faCode(tempForm).then((data) => {
        ElMessage.success(data.message);
        store.commit("setLoggedUser", data.data);
        router.push("/");
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const refreshCode = () => {
  t.value = Math.random();
  captcha.value = `${baseURL}/captcha?t=${t.value}`;
};
onMounted(refreshCode);
</script>

<style scoped>
.bt-login {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
